package com.bls.cate_s.servlet;

import com.bls.cate_s.model.Root;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;


/**
 * 使用反射的方法获得网络请求方法 key = "RequestType"   value = "???"  此参数必填
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doGet(req, resp);
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String methodName = req.getParameter("RequestType");
        if (null == methodName)
            methodName = "execute";
        System.out.println("BaseServlet : " + this + " , " + methodName);
        try {
            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            Root root = (Root) method.invoke(this, req, resp);
            JSONObject json = new JSONObject();
            json.put("result", root);
            resp.getWriter().write(json.toJSONString());
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("请求的方法[" + methodName + "]不存在");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("服务器异常", e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doPost(req, resp);
        this.doGet(req, resp);
    }

    /**
     * 此方法用于复写，方便子类编程，默认执行方法
     */
    public void execute(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }
}
